import React, { Component } from "react";
import { connect } from "react-redux";
import Selector from "components/selector";
import { messages, queryCurrencyPrecision } from "share/common";
import { Checkbox } from "antd";
import selectorData from "share/selectorData";
import { AdvancedTable } from "components/index";
import moment from "moment";
import httpFetch from "share/httpFetch";
import constant from "./constant";
import menuRoute from "routes/menuRoute";
import AccrualHistory from "./accrual-history";

class AccrualManagementView extends Component {
  statusOptions = Object.keys(constant.statusMap).map((item) => ({ label: constant.statusMap[item], value: item }));

  state = {
    searchForm: [
      {
        component: (isTitle) => (
          <Selector
            allowClear={false}
            type={"setOfBooksByTenant"}
            params={{ roleType: "TENANT" }}
            entity
            onChange={(value) => this.handleChangeSetOfBook(value, isTitle)}
          />
        ),
        id: "setOfBooksId",
        judgeInTitle: true,
        label: messages("finance-10.key27") /*批次账套*/,
        initialValue: {
          setOfBooksName: this.props.company.setOfBooksName,
          id: this.props.company.setOfBooksId,
        },
        tagUnclosed: true,
        parser: (value) => ({ setOfBooksId: value ? value.id : undefined }),
        tagParser: (value) => value.setOfBooksName,
      },
      {
        id: "companyId",
        label: messages("finance-10.key28") /*批次公司*/,
        component: "Chooser",
        props: {
          type: "available_company_setOfBooks",
          labelKey: "name",
          valueKey: "id",
          single: true,
          listExtraParams: {
            enabled: true,
            setOfBooksId: this.props.company.setOfBooksId,
          },
        },
        initialValue: [{ name: this.props.company.name, id: this.props.company.id }],
        parser: (value) => ({
          companyId: value && value.length ? value[0].id : null,
        }),
      },
      {
        id: "createdBy",
        label: messages("finance-10.key43") /*创建人*/,
        component: "Selector",
        props: {
          placeholder: messages("common.please.input") /*请输入*/ + messages("finance-10.key44") /*姓名/工号*/,
          selectorItem: {
            ...selectorData["user"],
            url: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
            label: (record) =>
              `${record.employeeID}-${record.fullName}${
                record.status !== 1001
                  ? `（${
                      record.status === 1002
                        ? messages("finance-1.key91") /*待离职员工*/
                        : messages("finance-1.key92") /*离职员工*/
                    }）`
                  : ""
              }`,
          },
        },
      },
      {
        id: "createdDate",
        label: messages("finance-10.key45") /*创建日期*/,
        component: "DateRangePicker",
        parser: (value) => ({
          createdDateFrom: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : undefined,
          createdDateTo: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : undefined,
        }),
        initialValue: [moment().subtract(1, "month"), moment()],
      },
      {
        id: "bookDate",
        label: messages("finance-10.key29") /*预提记账日期*/,
        component: "DateRangePicker",
        parser: (value) => ({
          bookDateFrom: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : undefined,
          bookDateTo: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : undefined,
        }),
        initialValue: [moment().subtract(1, "month"), moment()],
      },
      {
        id: "filterStatusList",
        label: messages("common.column.status") /*状态*/,
        component: (
          <Checkbox.Group>
            {this.statusOptions.map((item) => (
              <Checkbox key={item.value} value={item.value}>
                {item.label}
              </Checkbox>
            ))}
          </Checkbox.Group>
        ),
        tagParser: (value) =>
          this.statusOptions
            .filter((item) => value.find((key) => item.value === key))
            .map((item) => item.label)
            .join(","),
        row: true,
      },
    ],
  };

  handleChangeSetOfBook = (value, isTitle) => {
    const { searchForm } = this.state;
    let setOfBooksId = searchForm.find((item) => item.id === "companyId").props.listExtraParams.setOfBooksId;
    if (setOfBooksId !== value.id) {
      if (!isTitle) {
        this.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
          companyId: undefined,
        });
      }
      searchForm.map((item) => {
        if (item.id === "companyId") {
          item.props.listExtraParams = {
            setOfBooksId: value.id,
            enabled: true,
          };
        }
      });
      this.wrappedInstance.setState({ searchForm });
    }
  };

  service = (page, size, searchParams) => {
    return httpFetch.post(`/api/accrued/expense/batch/finance/query`, {
      page,
      size,
      ...searchParams,
    });
  };

  columns = [
    { title: messages("finance-10.key26") /*批次号*/, dataIndex: "batchNumber" },
    { title: messages("finance-10.key27") /*批次账套*/, dataIndex: "setOfBooksName" },
    { title: messages("finance-10.key28") /*批次公司*/, dataIndex: "companyName", width: 120, minWidth: 100 },
    {
      title: messages("finance-10.key45") /*创建日期*/,
      dataIndex: "createdDate",
      stableWidth: 120,
      render: (value) => (value ? moment(value).format("YYYY-MM-DD") : "-"),
    },
    {
      title: messages("finance-10.key46") /*创建人|工号*/,
      dataIndex: "operator",
      render: (value) => `${value.fullName}|${value.employeeID}`,
    },
    { title: messages("finance-10.key47") /*本币币种*/, dataIndex: "baseCurrencyCode", stableWidth: 100 },
    {
      title: messages("finance-10.key48") /*本币总预提金额*/,
      dataIndex: "baseAmount",
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode)),
    },
    {
      title: messages("finance-10.key29") /*预提记账日期*/,
      dataIndex: "bookDate",
      render: (value) => (value ? moment(value).format("YYYY-MM-DD") : "-"),
    },
    {
      title: messages("finance-10.key30") /*预提冲销记账日期*/,
      dataIndex: "reverseBookDate",
      render: (value) => (value ? moment(value).format("YYYY-MM-DD") : "-"),
    },
    {
      title: messages("common.column.status") /*状态*/,
      dataIndex: "status",
      render: (value) => constant.statusMap[value],
    },
    {
      title: messages("common.operation") /*操作*/,
      dataIndex: "operation",
      minWidth: 120,
      render: (value, record) => (
        <span>
          <a onClick={() => this.onViewHistory(record)}>{messages("finance-10.key22") /*预提历史*/}</a>
          <span className="ant-divider" />
          <a onClick={() => this.onViewDetail(record)}>{messages("finance-10.key31") /*查看明细*/}</a>
          <span className="ant-divider" />
          <a onClick={() => this.onViewTotal(record)}>{messages("finance-10.key32") /*查看汇总*/}</a>
        </span>
      ),
    },
  ];

  onViewHistory = (record) => {
    AccrualHistory.open(this, {
      accruedExpenseBatchId: record.accruedExpenseBatchId,
    });
  };

  onViewDetail = (record) => {
    this.context.router.push(
      menuRoute.getRouteItem("detail-view").url.replace(":accruedExpenseBatchId", record.accruedExpenseBatchId)
    );
  };

  onViewTotal = (record) => {
    this.context.router.push(
      menuRoute.getRouteItem("total-view").url.replace(":accruedExpenseBatchId", record.accruedExpenseBatchId)
    );
  };

  render() {
    const { searchForm } = this.state;
    return (
      <AdvancedTable
        service={this.service}
        title={messages("finance-10.key55") /*预提批次查看*/}
        tableName={"accrual-management-view"}
        columns={this.columns}
        searchForm={searchForm}
        rowKey="accruedExpenseBatchId"
      />
    );
  }
}

AccrualManagementView.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    company: state.login.loginCompany,
  };
}

export default connect(mapStateToProps)(AccrualManagementView);
